package com.liruo.enumconverter.test.web.config;

import com.liruo.enumconverter.model.SourceEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SourceEnumTypeHandler<E extends SourceEnum<?>> extends BaseTypeHandler<E> {
    private final Class<E> type;
    private final boolean isInt;

    public SourceEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.isInt = type.getEnumConstants()[0].source() instanceof Integer;
            this.type = type;
        }
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            if(isInt){
                ps.setInt(i, (Integer) parameter.source());
            }else{
                ps.setString(i, (String) parameter.source());
            }
        } else {
            ps.setObject(i, parameter.source(), jdbcType.TYPE_CODE);
        }

    }
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object source = isInt ? rs.getInt(columnName) : rs.getString(columnName);
        for (E enumConstant : type.getEnumConstants()) {
            if(enumConstant.source().equals(source)){
                return enumConstant;
            }
        }
        return null;
    }
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object source = isInt ? rs.getInt(columnIndex) : rs.getString(columnIndex);
        for (E enumConstant : type.getEnumConstants()) {
            if(enumConstant.source().equals(source)){
                return enumConstant;
            }
        }
        return null;
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object source = isInt ? cs.getInt(columnIndex) : cs.getString(columnIndex);
        for (E enumConstant : type.getEnumConstants()) {
            if(enumConstant.source().equals(source)){
                return enumConstant;
            }
        }
        return null;
    }
}
